package yasuo;

import java.io.File;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.GZip;
import org.apache.tools.ant.taskdefs.Tar;
import org.apache.tools.ant.taskdefs.Tar.TarFileSet;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;

/**
 * @ClassName: ZipCompressorByAnt
 * @CreateTime Apr 28, 2013 1:23:45 PM
 * @author : Mayi
 * @Description: 压缩文件的通用工具类-采用ant中的org.apache.tools.ant.taskdefs.Zip来实现，更加简单。
 * 
 */
public class CompressorByAnt {

	/**
	 * 执行压缩操作，将文件/文件夹压缩成zip格式
	 * 
	 * @param srcPathName
	 *            需要被压缩的文件/文件夹
	 */
	public static void compressToZip(String srcPathName, String targetPathName) {
		File src = new File(srcPathName);
		File targetFile = new File(targetPathName);
		
		if (!src.exists()) {
			throw new RuntimeException(srcPathName + "不存在！");
		}

		Project prj = new Project();
		
		FileSet fileSet = new FileSet();
		fileSet.setProject(prj);
		if(src.isDirectory()){
			fileSet.setDir(src);
		}else{
			fileSet.setFile(src);
		}
		// fileSet.setIncludes("**/*.java"); //包括哪些文件或文件夹
		// fileSet.setExcludes(...); //排除哪些文件或文件夹
		
		Zip zip = new Zip();
		zip.setProject(prj);
		zip.setDestFile(targetFile);
		zip.addFileset(fileSet);
		zip.execute();
	}
	
	private static void compressToTar(String srcPathName, String targetPathName) {
		File src = new File(srcPathName);
		File targetFile = new File(targetPathName);
		
		if (!src.exists()) {
			throw new RuntimeException(srcPathName + "不存在！");
		}
		
		Project prj = new Project();
		Tar tar = new Tar();
		tar.setProject(prj);
		tar.setDestFile(targetFile);
		TarFileSet tarFileSet = tar.createTarFileSet();
		if(src.isDirectory()){
			tarFileSet.setDir(src);
		}else{
			tarFileSet.setFile(src);
		}
		
		tar.execute();
	}
	
	private static void compressToGz(String srcPathName) {
		File src = new File(srcPathName);
		File targetFile = new File(srcPathName+".gz");
		
		if (!src.exists()) {
			throw new RuntimeException(srcPathName + "不存在！");
		}
		
		Project prj = new Project();
		
		GZip gZip = new GZip();
		gZip.setProject(prj);
		gZip.setDestfile(targetFile);
		gZip.setSrc(src);
		
		gZip.execute();
	}
	
	public static void compressToTarGz(String srcPathName, String tarPathName) {
		compressToTar(srcPathName, tarPathName);
		compressToGz(tarPathName);
		new File(tarPathName).delete();
	}
	
	
	public static void main(String[] args) {
//		CompressorByAnt.compressToZip("E:\\var", "E:\\test.zip");
		CompressorByAnt.compressToTarGz("E:\\var", "E:\\test2.tar");
//		CompressorByAnt.compressToTar("E:\\var", "E:\\test.tar");
	}

}